/**
 * @Author: easten
 * @Created: 2024-04-15 23:48:14
 * @Description:
 *
 */
import { ApiDict } from "_common/api/sys";
import { DrawerProps } from "_common/DataType";
import { SysDict } from "_common/entity";
import React, { useEffect, useRef } from "react";
import {
  Button,
  Drawer,
  Form,
  FormInstanceFunctions,
  Input,
} from "tdesign-react";
import FormItem from "tdesign-react/es/form/FormItem";
type DictDrawerProps = DrawerProps & {
  isChildren?: boolean;
  parentId?: number;
};
const DictDrawer: React.FC<DictDrawerProps> = (props: DictDrawerProps) => {
  const { open, parentId, edit, onSuccess, value, isChildren, axios } = props;
  const formRef = useRef<FormInstanceFunctions>();
  const apiDict = new ApiDict(axios!);
  useEffect(() => {
    return () => {
      formRef.current?.reset();
    };
  }, []);

  useEffect(() => {
    if (value && edit) {
      formRef.current?.setFieldsValue(value);
    }
  }, [edit, value]);

  const handleClose = () => {
    onSuccess?.(false);
    formRef.current?.reset();
  };

  // 新增
  const createDict = async (data: SysDict) => {
    if (isChildren) {
      if (parentId) {
        data.parentId = parentId;
      } else {
        console.error("请选择父级！");
        return;
      }
    }
    const response = await apiDict.createDict(data);
    if (response && response.code == 200 && response.data) {
      handleClose();
    }
  };
  // 更新
  const updateDict = async (data: SysDict) => {
    const response = await apiDict.updateDict({
      ...data,
      id: value?.id,
      parentId: value?.parentId,
    });
    if (response && response.code == 200 && response.data) {
      handleClose();
    }
  };

  return (
    <Drawer
      header={`${edit ? "编辑" : "添加"}字典`}
      footer={false}
      visible={open}
      sizeDraggable
      size="medium"
      onClose={handleClose}
    >
      <Form
        ref={formRef}
        labelWidth={100}
        onSubmit={(data) => {
          edit
            ? updateDict(data.fields as SysDict)
            : createDict(data.fields as SysDict);
        }}
      >
        <FormItem
          label="字典名称"
          rules={[{ required: true }]}
          name="dictLabel"
        >
          <Input />
        </FormItem>
        <FormItem label="字典编码" name="dictCode" rules={[{ required: true }]}>
          <Input />
        </FormItem>
        <FormItem label="字典值" rules={[{ required: false }]} name="dictValue">
          <Input placeholder="字典编码唯一，不要随意改动" />
        </FormItem>
        <FormItem className="float-right">
          <Button type="submit" theme="primary">
            提交
          </Button>
          <Button type="reset" theme="success" style={{ marginLeft: 12 }}>
            重置
          </Button>
        </FormItem>
      </Form>
    </Drawer>
  );
};
export default DictDrawer;
